<template>
  <div class="login-box">
    <el-form ref="loginFormRef" :model="loginForm" :rules="loginFormRules" label-width="70px" class="loginForm"
      status-icon>
      <h1 class="title">后台管理系统</h1>
      <el-form-item label="账号:" prop="userName">
        <el-input v-model="loginForm.userName" autocomplete="off" />
      </el-form-item>
      <el-form-item label="密码:" prop="password">
        <el-input v-model="loginForm.password" type="password" autocomplete="off" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" class="sub-btn" @click="onSubmitBtnClick">登录</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang="ts">
import { defineComponent, reactive, toRefs } from 'vue'
import { InitData } from '@/types/login'
import { login } from '@/api/login'
import { useRouter } from 'vue-router';
import { AxiosResponse } from 'axios'

export default defineComponent({
  setup() {
    // 拿到路由器对象
    const router = useRouter()
    // 数据
    const data = reactive(new InitData())
    // 登录表单校验规则
    const loginFormRules = {
      userName: [
        { required: true, message: '请输入账号', trigger: 'blur' },
        { min: 6, max: 24, message: '账号长度需要在6~24位之间', trigger: 'blur' }
      ],
      password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, max: 24, message: '密码长度需要在6~24位之间', trigger: 'blur' }
      ]
    }

    // 处理函数，当提交按钮被点击时触发
    const onSubmitBtnClick = async () => {
      try {
        // // 调用表单实例对象上的自定义校验方法对表单数据进行校验
        await data.loginFormRef?.validate()
        // 如果校验通过，则发送请求
        let res: AxiosResponse = await login(data.loginForm)
        // 如果请求失败，则终止函数执行
        // if (res.code !== 200) return
        // 将token数据保存到本地
        localStorage.setItem("token", res.data.token)
        // 跳转到首页
        // router.push('/')
      } catch (error) {
        return console.error(error);
      }
    }

    return {
      ...toRefs(data),
      loginFormRules,
      onSubmitBtnClick,
    }
  }
})
</script>

<style lang="scss" scoped>
.login-box {
  width: 100%;
  height: 100%;
  background: url('../assets/bg.jpg') no-repeat center/cover;
  box-sizing: border-box;
  padding-top: 200px;

  .loginForm {
    width: 400px;
    padding: 20px;
    background: #fff;
    border-radius: 20px;
    margin: 0 auto;

    .sub-btn {
      width: 100%;
    }

    .title {
      text-align: center;
      margin: 20px;
    }
  }
}
</style>